package com.ruitu.mall_98.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.beanu.arad.Arad;
import com.beanu.arad.base.ToolBarFragment;
import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.base.my_base.WineRefreshHeader;
import com.beanu.arad.base.my_base.base_list.ListBaseAdapter;
import com.beanu.arad.base.my_base.base_list.SuperViewHolder;
import com.beanu.arad.utils.Logg;
import com.beanu.arad.utils.SHA1;
import com.beanu.arad.utils.ScreenUtils;
import com.beanu.arad.utils.SizeUtils;
import com.beanu.arad.utils.ToastUtils;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnItemLongClickListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ruitu.mall_98.MainActivity;
import com.ruitu.mall_98.R;
import com.ruitu.mall_98.adapter.HorizontalDataAdapter;
import com.ruitu.mall_98.adapter.ModelAdapter;
import com.ruitu.mall_98_1.mvp.contract.MainHomeContract;
import com.ruitu.mall_98_1.mvp.model.MainHomeModelImpl;
import com.ruitu.mall_98_1.mvp.presenter.MainHomePresenterImpl;
import com.ruitu.mall_98_1.product.activity.CouponForGiftActivity;
import com.ruitu.mall_98_1.product.activity.CouponListPlatformActivity;
import com.ruitu.mall_98_1.product.activity.ProductListByModelActivity;
import com.ruitu.mall_98_1.product.activity.ProductListBySearchActivity;
import com.ruitu.mall_98_1.product.support.AlertUtil;
import com.ruitu.router_module.A_Rutils;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.bean.DataAdapter;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.app.Area;
import com.ruitu.router_module.bean.app.BannerNew;
import com.ruitu.router_module.bean.app.HeadClass;
import com.ruitu.router_module.bean.app.HomeData;
import com.ruitu.router_module.bean.app.HomeModel;
import com.ruitu.router_module.bean.product.ProHome;
import com.ruitu.router_module.bean.product.Product;
import com.ruitu.router_module.bean.product.SearchCondition;
import com.ruitu.router_module.utils.GlideImageLoader;
import com.ruitu.router_module.utils.RcvUtils;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import cn.jpush.android.api.JPushInterface;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

/**
 * Created by Administrator on 2018.08.17.
 */
public class MainHomeFragment extends ToolBarFragment<MainHomePresenterImpl, MainHomeModelImpl> implements MainHomeContract.View {
    private LRecyclerView recyclerView;
    private FrameLayout home_title_bar_layout;//主页顶部title
    private View home_title_bar_bg_view;//顶部title背景view
    private com.youth.banner.Banner banner;
    private ImageView iv_banner_holder;//banner的占位图
    private RecyclerView rcv_10_menu, rcv_8_model;//10个菜单项的布局,八大模块的布局
    private RecyclerView lh_recyclerview;//横向滑动商品列表
    private LinearLayout scan_layout, ll_search;//标题栏左上角的,搜索
    private RelativeLayout msg_layout;//右上角消息
    private TextView tv_location;//位置/城市

    private List<ProHome> proHomeList = new ArrayList<>();//底部商品列表
    private DataAdapter dataAdapter;//LRecyclerView的adapter
    private LRecyclerViewAdapter lAdapter;
    private MenuAdapter menuAdapter;//10个菜单项的布局adapter
    private ModelAdapter modelAdapter;//八大模块的adapter

    private List<HeadClass> classList = new ArrayList<>();//首页十个菜单项
    private HorizontalDataAdapter mDataAdapter;//横向滑动商品adapter 精品专场adapter
    private List<BannerNew> jingxuanList = new ArrayList<>();//精品专场的数据
    List<List<HomeModel>> homeModelList = new ArrayList<>();//八个模块的数据列表

    private int SCREEN_WIDTH = 0;//屏幕的宽度
    private boolean isRefreshed = false;//是否已经下拉刷新

    private HomeData homeData;//存储首页需要的数据

    public static MainHomeFragment newInstance() {
        Bundle args = new Bundle();
        MainHomeFragment fragment = new MainHomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    private BDLocation currLoc;
    private boolean isLoc = false;//是否已经定位过
    public static boolean IS_NEED_LODCATION = true;//是否需要定位

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetEvent(EventModel e) {
        if (e.getEventCode() == 18111251) {//切换了城市
            tv_location.setText(AppHolder.instance().getCITY().getName());
            hideProgress();
            showProgress();
            reqHomeData(AppHolder.instance().getCITY().getName());
        }
        if (e.getEventCode() == 18120351) {//收到定位成功的消息
            Logg.i("收到定位的消息");
            currLoc = (BDLocation) e.getEventObj();
            if (!isDataEmpty(homeData.getCityList())) {//有已开通的省份
                for (int i = 0; i < homeData.getCityList().size(); i++) {
                    Area pro = homeData.getCityList().get(i);
                    if (!isDataEmpty(pro.getCityList())) {
                        for (int j = 0; j < pro.getCityList().size(); j++) {
                            Area city = pro.getCityList().get(j);
                            city.setParentName(pro.getName());
                            String cityName = city.getName();
                            if (TextUtils.equals(cityName, currLoc.getCity()) || cityName.contains
                                    (currLoc.getCity()) || currLoc.getCity().contains(cityName)) {
                                AppHolder.instance().setCITY(city);
                                saveCityInfo(city.getName(), city.getId(), city.getParentName(), city.getParentId());
                                Arad.bus.post(new EventModel(19012252));//根据城市名,通知分类页面请求分类数据
                                //说明当前定位的城市是已开通城市
                                tv_location.setText(cityName);
                                reqHomeData(cityName);
                                return;
                            }
                        }
                    }
                }
            } else {
                //没有已开通的城市
            }
        }
        if (e.getEventCode() == 18110900 || e.getEventCode() == 18080251) {//登录成功或者需要主动请求连接融云
//            String appKey = "z3v5yqkbz1by0";
            String appKey = "sfci50a7s3osi";
            String uuid = UUID.randomUUID().toString();
            String nonce = uuid;
            String timeStamp = System.currentTimeMillis() + "";
//            String signiture = SHA1.encode("uqeGygaAGo" + nonce + timeStamp);
            String signiture = SHA1.encode("PzxRAJWcxTRY" + nonce + timeStamp);
            String userId = AppHolder.instance().getUser().getAccountId();
            String userName = AppHolder.instance().getUser().getNickName();
            String portrait = Config.BASE_URL + AppHolder.instance().getUser().getImageUrl();
            if (TextUtils.isEmpty(portrait)) {
                portrait = "...";
            }
            mPresenter.connectRong(appKey, nonce, timeStamp, signiture, userId, userName, portrait);

            String uId9 = userId.substring(0, 9);
            int sequence = Integer.parseInt(uId9);
            JPushInterface.setAlias(Arad.app, sequence, userId);// 极光别名
        }
        if (e.getEventCode() == 18122001) {//购物车为空,去逛逛,跳到第一个页面
            ((MainActivity) getActivity()).setCurrVp(0);
        }
        if (e.getEventCode() == 19010253) {//收到新的通知,刷新
            if (CommonUtils.isLogin()) {
                mPresenter.reqUnReadNum(AppHolder.instance().getUser().getAccountId());
            }
        }
    }

    private AlertDialog alertSection;//选择城市的弹窗 chat/getUserInfo
    private AlertDialog alertCoupon;//大礼包的弹窗

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SCREEN_WIDTH = ScreenUtils.getScreenWidth();//获取屏幕宽度
        Arad.bus.register(this);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                showDialogCoupon();//大礼包弹窗  200415 暂时关闭大礼包弹窗
            }
        }, 2000);
    }

    private View header1, header2, header3_3, header4;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_main_home, container, false);
        recyclerView = v.findViewById(R.id.recyclerView);
        home_title_bar_layout = v.findViewById(R.id.home_title_bar_layout);
        home_title_bar_bg_view = v.findViewById(R.id.home_title_bar_bg_view);
        scan_layout = v.findViewById(R.id.scan_layout);
        tv_location = v.findViewById(R.id.tv_location);
        ll_search = v.findViewById(R.id.ll_search);
        msg_layout = v.findViewById(R.id.msg_layout);

        alertSection = new AlertDialog.Builder(getActivity(), R.style.Dialog_FS).create();
        alertCoupon = new AlertDialog.Builder(getActivity(), R.style.Dialog_FS).create();

        //Banner的布局
        header1 = inflater.inflate(R.layout.home_banner_layout, null, false);
        banner = header1.findViewById(R.id.banner);//Banner布局
        iv_banner_holder = header1.findViewById(R.id.iv_banner_holder);//Banner布局占位图
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) banner.getLayoutParams();
        params.width = SCREEN_WIDTH;
        params.height = params.width * 900 / 1800;//banner的比例是1800 * 900
        banner.setLayoutParams(params);
        iv_banner_holder.setLayoutParams(params);

        //菜单项的布局
        header2 = inflater.inflate(R.layout.home_menu_layout_grid, null, false);
        rcv_10_menu = header2.findViewById(R.id.rcv_10_menu);
        menuAdapter = new MenuAdapter(getActivity());
        GridLayoutManager manager5 = new GridLayoutManager(getActivity(), 5);
        rcv_10_menu.setLayoutManager(manager5);
        rcv_10_menu.setAdapter(menuAdapter);
        for (int i = 0; i < 10; i++) {
            classList.add(new HeadClass());
        }
        menuAdapter.setDataList(classList);

        //八个布局的模块
        header3_3 = inflater.inflate(R.layout.home_8_model_layout, null, false);
        rcv_8_model = header3_3.findViewById(R.id.rcv_8_model);
        modelAdapter = new ModelAdapter(getActivity());
        LinearLayoutManager manager33 = new LinearLayoutManager(getActivity());
        manager33.setOrientation(LinearLayoutManager.VERTICAL);
        rcv_8_model.setLayoutManager(manager33);
        rcv_8_model.setAdapter(modelAdapter);

        //精品专场
        header4 = inflater.inflate(R.layout.home_cheap_product_layout, null, false);
        lh_recyclerview = header4.findViewById(R.id.lh_recyclerview);

        initLRecyclerView();
        initRecyclerViewHorizon();

        lAdapter.addHeaderView(header1);//添加Banner布局
        lAdapter.addHeaderView(header2);//添加功能菜单布局
        lAdapter.addHeaderView(header4);//精品专场
        lAdapter.addHeaderView(header3_3);//八大模块

        setListeners();//设置一些监听
        showProgress();
        initHomeData();//初始化及请求首页数据
        return v;
    }

    private void initHomeData() {
        String cityName = Arad.preferences.getString(Config.SAVE_CITY_KEY);
        if (TextUtils.isEmpty(cityName)) {
            cityName = "全国版";
        }
        Area city = new Area();
        city.setName(cityName);
        city.setId(Arad.preferences.getString(Config.SAVE_CITY_ID));
        city.setParentName(Arad.preferences.getString(Config.SAVE_CITY_PA_NAME));
        city.setParentId(Arad.preferences.getString(Config.SAVE_CITY_PA_ID));
        AppHolder.instance().setCITY(city);
        tv_location.setText(cityName);
        reqHomeData(cityName);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Arad.bus.post(new EventModel(19012252));//根据城市名,通知分类页面请求分类数据
            }
        }, 200);
    }

    private void setListeners() {
        menuAdapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int pos) {
                if (pos < 8) {
                    try {
                        Intent intent = new Intent(getActivity(), ProductListByModelActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("type", homeModelList.get(pos).get(0).getType());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } catch (Exception e) {
                        ToastUtils.showShort("暂无商品");
                    }
                } else if (pos == 8) {
                    startActivity(CouponListPlatformActivity.class);
                } else if (pos == 9) {
                    ((MainActivity) getActivity()).setCurrVp(4);//切换到个人中心页面
                }
            }
        });
        scan_layout.setOnClickListener(this);
        ll_search.setOnClickListener(this);
        msg_layout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == scan_layout) {//左上角的切换城市
            if (null != homeData) {
                if (!isDataEmpty(homeData.getCityList())) {
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("city_list", (Serializable) homeData.getCityList());
//                    startActivity(CityListActivity.class, bundle);
                    showDialogSection();//选择城市
                } else {
                    ToastUtils.showShort("暂时没有开通的城市");
                }
            } else {
                ToastUtils.showShort("数据加载中,请稍候重试");
            }
        }
        if (v == ll_search) {//搜索
            try {
                A_Rutils.startActivity(getActivity(), "com.ruitu.mall_98_1.search.SearchActivity");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (v == msg_layout) {//消息 启动会话列表界面
//            startActivity(MsgActivity.class);
            ((MainActivity) getActivity()).setCurrVp(2);
        }
    }

    private void initRecyclerViewHorizon() {//精品专场
        mDataAdapter = new HorizontalDataAdapter(getActivity());
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        lh_recyclerview.setLayoutManager(manager);
        lh_recyclerview.setAdapter(mDataAdapter);
    }

    private void initLRecyclerView() {
        if (null != recyclerView) {
//            recyclerView.addItemDecoration(new GridDecoration(SizeUtils.dp2px(10)));
            WineRefreshHeader header = new WineRefreshHeader(getActivity());
            header.setHintTextColor(com.beanu.arad.R.color.l_rcv_color);
//            header.setViewBackgroundColor(R.color.white);
            recyclerView.setRefreshHeader(header);
            header.setOnPullListener(new WineRefreshHeader.OnPullListener() {
                @Override
                public void onPull(float offSet, float sumOffSet) {
                    if (sumOffSet > 10) {
                        showTitleBar(false);
                    }
                }

                @Override
                public void onReset() {
                    home_title_bar_layout.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            showTitleBar(true);
                        }
                    }, 330);
                }
            });

            GridLayoutManager manager = new GridLayoutManager(getActivity(), 2);
//            LinearLayoutManager manager = new LinearLayoutManager(getActivity());
//            manager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(manager);

            dataAdapter = new DataAdapter(getActivity());
            lAdapter = new LRecyclerViewAdapter(dataAdapter);
            recyclerView.setAdapter(lAdapter);
//            setLoadMoreEnabled(false);//默认不开启加载更多功能
//            recyclerView.setFooterViewHint("努力加载中", "加载完成", "加载失败,点击重试");//底部文字提示
            recyclerView.setLoadMoreEnabled(false);

            recyclerView.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh() {
                    isRefreshed = false;//正在刷新

                    //下拉刷新的时候请求数据
                    reqHomeData(AppHolder.instance().getCITY().getName());
                    RcvUtils.refreshCompleteDelay(recyclerView, new RcvUtils.OnRefreshListener() {
                        @Override
                        public void onRefreshComplete() {
                            isRefreshed = true;//刷新完成
                            home_title_bar_bg_view.setBackgroundColor(0);
                        }
                    });
                }
            });

            recyclerView.setLScrollListener(new LRecyclerView.LScrollListener() {
                public void onScrollUp() {
                }

                public void onScrollDown() {
                }

                public void onScrolled(int distanceX, int distanceY) {
                    int myDis = -header1.getTop();//header1距离顶部的距离替代distanceY
                    if (myDis > 0) showTitleBar(true);
                    if (myDis >= SizeUtils.dp2px(50)) {//滑动50dp后开始变色
                        home_title_bar_bg_view.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                        home_title_bar_bg_view.setAlpha(myDis * 1.0f / SizeUtils.dp2px(120));//120dp后不透明
                    } else {
                        home_title_bar_bg_view.setBackgroundColor(0);
                    }

                    if (recyclerView.isOnTop()) {
                        home_title_bar_bg_view.setAlpha(0);
                    }
                }

                public void onScrollStateChanged(int state) {
                }
            });
        }
        if (null != lAdapter) {//点击和长按事件
            lAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(View v, int pos) {
                    try {
                        Bundle bundle = new Bundle();
                        Product p = new Product();
                        p.setGoodId(proHomeList.get(pos).getGoodsId());
                        bundle.putSerializable("product", p);
                        A_Rutils.startActivity(getActivity(), "com.ruitu.mall_98_1.product.activity.ProductDetailActivity", bundle);
                    } catch (ClassNotFoundException e) {
                        ToastUtils.showShort("启动页面失败");
                    }
                }
            });
            lAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
                @Override
                public void onItemLongClick(View v, int pos) {
                }
            });
        }
    }

    private void initBanner(final List<BannerNew> bannerList) {
        List<String> urlList = new ArrayList<>();//图片地址集合
        List<String> introList = new ArrayList<>();//简介集合
        if (!isDataEmpty(bannerList)) {
            for (BannerNew banner : bannerList) {
                urlList.add(Config.BASE_URL + banner.getImgApp());
                introList.add("");//不显示banner简介
            }
        }

        if (isDataEmpty(urlList)) {
            banner.setVisibility(View.GONE);
            iv_banner_holder.setVisibility(View.VISIBLE);
            return;
        } else {
            banner.setVisibility(View.VISIBLE);
            iv_banner_holder.setVisibility(View.GONE);
        }
        try {
            banner.setImages(urlList);//设置图片集合
            banner.setImageLoader(new GlideImageLoader());//设置图片加载器
            banner.setDelayTime(6000);//设置轮播时间
            banner.setIndicatorGravity(BannerConfig.RIGHT);
            banner.setBannerAnimation(Transformer.Accordion);
            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int pos) {
                    Intent intent = new Intent(getActivity(), ProductListByModelActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("type", bannerList.get(pos).getId());
                    bundle.putString("model_name", bannerList.get(pos).getName());
                    intent.putExtras(bundle);
                    startActivity(intent, bundle);
                }
            });
            banner.start();//banner设置方法全部调用完毕时最后调用
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showTitleBar(boolean isShow) {
        if (isShow) {
            if (home_title_bar_layout.getVisibility() == View.GONE) {
                home_title_bar_layout.setVisibility(View.VISIBLE);
            }
        } else {
            if (home_title_bar_layout.getVisibility() == View.VISIBLE) {
                home_title_bar_layout.setVisibility(View.GONE);
            }
        }
    }

    //请求首页数据
    private void reqHomeData(String cityName) {
        String accountId = "";
        if (CommonUtils.isLogin()) {
            accountId = AppHolder.instance().getUser().getAccountId();
        }
        mPresenter.reqAppHome(cityName, accountId);
    }

    @Override
    public void onReqComplete(boolean isSuc, int type, Object data) {//请求数据完成时的回调
        if (type == 1) {//首页数据
            hideProgress();
            handleHomeData((HomeData) data);
            isRefreshed = true;
            initBanner(homeData.getAppBanner());//设置Banner
            setJingXuanData();//设置精品专场
            proHomeList = homeData.getFootprints();
            dataAdapter.setDataList(proHomeList);

            if (!isDataEmpty(proHomeList)) {
//                View footer_more = inflater.inflate(R.layout.home_more_pro_view, null, false);
                View footer_more = View.inflate(getActivity(), R.layout.home_more_pro_view, null);
                footer_more.findViewById(R.id.tv_more).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        SearchCondition condition = new SearchCondition();
                        condition.setCityName(AppHolder.instance().getCITY().getName());
                        bundle.putSerializable("condition", condition);
                        startActivity(ProductListBySearchActivity.class, bundle);
                    }
                });
                lAdapter.addFooterView(footer_more);
            }
            AppHolder.instance().setGlobalProList(proHomeList);
            if (!isLoc) {
                ((MainActivity) getActivity()).startLoc();
                isLoc = false;
            }
            Arad.bus.post(new EventModel(18122751));
        } else if (type == 2) {//融云连接成功
            getUnReadMsgNum();//收到消息,获取未读消息数量
            RongIM.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
                @Override
                public boolean onReceived(io.rong.imlib.model.Message message, int i) {
                    getUnReadMsgNum();//收到消息,获取未读消息数量
                    return false;
                }
            });
        } else if (type == 3) {//收到未读消息数量
            try {
                sysMsgNum = (int) data;
                Arad.bus.post(new EventModel(19010252, sysMsgNum));//系统消息数量
            } catch (Exception e) {
                e.printStackTrace();
            }
            ((MainActivity) getActivity()).addBadge(2, sysMsgNum
                    + rongMsgNum);//显示未读消息数量
        }
    }

    private int rongMsgNum = 0;//融云消息数量
    private int sysMsgNum = 0;//系统消息数量

    //获取融云未读消息数量
    private void getUnReadMsgNum() {
        RongIMClient.getInstance().getTotalUnreadCount(new RongIMClient.ResultCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                rongMsgNum = integer;
                Arad.bus.post(new EventModel(19010251, integer));//融云消息数量
                if (CommonUtils.isLogin()) {
                    mPresenter.reqUnReadNum(AppHolder.instance().getUser().getAccountId());
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getUnReadMsgNum();//获取未读消息数量
    }

    private void setJingXuanData() {
        jingxuanList.clear();
        jingxuanList.addAll(homeData.getJpzc());
        mDataAdapter.setDataList(jingxuanList);
    }

    private void handleHomeData(HomeData data) {
        homeData = data;
        homeModelList.clear();
        try {
            homeModelList.add(0, homeData.getDfts());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            homeModelList.add(1, homeData.getTyt());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            homeModelList.add(2, homeData.getGyg());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            homeModelList.add(3, homeData.getChj());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            homeModelList.add(4, homeData.getCjqc());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //以前地方特产在这个位置
        try {
            homeModelList.add(5, homeData.getHyjp());
        } catch (Exception e) {
        }
        try {
            homeModelList.add(6, homeData.getTjsp());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            homeModelList.add(7, homeData.getJjxsj());
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            modelBannerList.clear();
            genModelBanners(homeData.getTszc().get(0));
            genModelBanners(homeData.getTszc().get(1));
            genModelBanners(homeData.getTszc().get(2));
            genModelBanners(homeData.getTszc().get(3));
            genModelBanners(homeData.getTszc().get(4));
            //以前地方特产在这个位置
            genModelBanners(homeData.getTszc().get(5));
            genModelBanners(homeData.getTszc().get(6));
            genModelBanners(homeData.getTszc().get(7));
        } catch (Exception e) {
            genModelBanners(null);
            e.printStackTrace();
        }
        modelAdapter.modelBanner = modelBannerList;//为adapter设置Banner数据
        //模块类型（2，淘一淘；3，逛一逛；4，吃货街；5，厂家清仓；6，地方特产；7，行业精品；8，推荐商品，9，家居小世界）
        modelAdapter.setDataList(homeModelList);
    }

    List<BannerNew> modelBannerList = new ArrayList<>();

    //生成model的banner数据 (后来这些模块统一叫特色专场)
    private void genModelBanners(BannerNew modelBanner) {
        try {
            if (null != modelBanner) {
                modelBannerList.add(modelBanner);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private View alert_view_section;//对话框的布局,区间价

    public void showDialogSection() {//选择城市弹窗
        if (null == homeData) {
            ToastUtils.showShort("数据加载中,请稍候");
            return;
        }
        if (isDataEmpty(homeData.getCityList())) {
            ToastUtils.showShort("暂无已开通城市");
            return;
        }
        if (!TextUtils.equals("全国版", homeData.getCityList().get(0).getName())) {
            Area sCity = new Area();
            sCity.setName("全国版");
            sCity.setId("");
            sCity.setParentName("");
            sCity.setParentId("");
            homeData.getCityList().add(0, sCity);
        }
        alertSection.show();
        alert_view_section = View.inflate(getActivity(), R.layout.home_alert_choose_city, null);

        alert_view_section.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertSection.dismiss();//点击选择城市的关闭按钮
            }
        });

        final TextView tv_city_title = alert_view_section.findViewById(R.id.tv_city_title);
        final TextView tv_sel_pro = alert_view_section.findViewById(R.id.tv_sel_pro);
        final TextView tv_sel_city = alert_view_section.findViewById(R.id.tv_sel_city);
        final View flag_p = alert_view_section.findViewById(R.id.flag_p);
        final View flag_c = alert_view_section.findViewById(R.id.flag_c);

        String n = AppHolder.instance().getCITY().getName();
        if (TextUtils.isEmpty(n)) {
            tv_city_title.setText("当前：" + "暂无");
        } else {
            tv_city_title.setText("当前：" + n);
        }

        RecyclerView rcv_province = alert_view_section.findViewById(R.id.rcv_province);
        rcv_province.setLayoutManager(new LinearLayoutManager(getActivity()));
        AreaAdapter pAdapter = new AreaAdapter(getActivity());
        rcv_province.setAdapter(pAdapter);
        pAdapter.setDataList(homeData.getCityList());
        pAdapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, final int p_position) {
                flag_p.setVisibility(View.INVISIBLE);
                flag_c.setVisibility(View.VISIBLE);
                if (p_position == 0) {//点击全国版
                    Area city = homeData.getCityList().get(p_position);
                    AppHolder.instance().setCITY(city);
                    saveCityInfo(city.getName(), city.getId(), city.getParentName(), city.getParentId());
                    Arad.bus.post(new EventModel(18111251));
                    alertSection.dismiss();//点击选择城市的关闭按钮

                    IS_NEED_LODCATION = false;//用户切换了城市,不需要再定位
                    Arad.bus.post(new EventModel(19012252));//切换城市,通知分类页面请求分类数据
                } else {
                    tv_sel_pro.setText(homeData.getCityList().get(p_position).getName());
                    tv_sel_city.setText("请选择");
                    RecyclerView rcv_city = alert_view_section.findViewById(R.id.rcv_city);
                    rcv_city.setLayoutManager(new LinearLayoutManager(getActivity()));
                    AreaAdapter cAdapter = new AreaAdapter(getActivity());
                    rcv_city.setAdapter(cAdapter);
                    cAdapter.setDataList(homeData.getCityList().get(p_position).getCityList());
                    cAdapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View itemView, int c_position) {
                            Area city = homeData.getCityList().get(p_position).getCityList().get(c_position);
                            city.setParentName(homeData.getCityList().get(p_position).getName());
                            tv_sel_city.setText(city.getName());
                            AppHolder.instance().setCITY(city);
                            saveCityInfo(city.getName(), city.getId(), city.getParentName(), city.getParentId());
                            Arad.bus.post(new EventModel(18111251));
                            alertSection.dismiss();//点击选择城市的关闭按钮

                            IS_NEED_LODCATION = false;//用户切换了城市,不需要再定位
                            Arad.bus.post(new EventModel(19012252));//切换城市,通知分类页面请求分类数据
                        }
                    });
                }
            }
        });
        AlertUtil.setAlertBottomInStyle(alertSection.getWindow(), alert_view_section, getActivity());
    }

    private View alert_view_coupon;

    public void showDialogCoupon() {//大礼包弹窗
        alertCoupon.show();
        alert_view_coupon = View.inflate(getActivity(), R.layout.home_coupon_layout, null);
        alert_view_coupon.findViewById(R.id.iv_coupon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(CouponForGiftActivity.class);
                alertCoupon.dismiss();
            }
        });
        alert_view_coupon.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertCoupon.dismiss();
            }
        });

        AlertUtil.setAlertCenterStyle(alertCoupon.getWindow(), alert_view_coupon, getActivity());
    }

    @Override
    public void hideProgress() {
        super.hideProgress();
        recyclerView.refreshComplete(20);
    }

    private void saveCityInfo(String cityName, String cityId, String paName, String paId) {
        Arad.preferences.putString(Config.SAVE_CITY_KEY, cityName).flush();//城市名称
        Arad.preferences.putString(Config.SAVE_CITY_ID, cityId).flush();//城市id
        Arad.preferences.putString(Config.SAVE_CITY_PA_NAME, paName).flush();//省份名称
        Arad.preferences.putString(Config.SAVE_CITY_PA_ID, paId).flush();//省份id
    }

    //banner下面的菜单项的adapter
    private class MenuAdapter extends ListBaseAdapter<HeadClass> {
        private String[] menuTitle = {"地方特产", "淘一淘", "逛一逛", "吃货街", "厂家清仓"
                , "行业精品", "推荐商品", "家居世界", "优惠券", "个人中心",};

        private int[] menuIcon = {R.drawable.home_ic_menu_4_dfts, R.drawable.home_ic_menu_0_tyt
                , R.drawable.home_ic_menu_1_gyg, R.drawable.home_ic_menu_2_chj, R.drawable.home_ic_menu_3_cjqc
                , R.drawable.home_ic_menu_5_hyjp, R.drawable.home_ic_menu_6_tjsp, R.drawable.home_ic_menu_7_jjsj
                , R.drawable.home_ic_menu_8_yhq, R.drawable.home_ic_menu_9_grzx};

        public MenuAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.home_item_menu;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int pos) {
            TextView tv_menu_txt = holder.getView(R.id.tv_menu_txt);
            ImageView iv_menu_icon = holder.getView(R.id.iv_menu_icon);

            tv_menu_txt.setText(menuTitle[pos]);
            iv_menu_icon.setImageResource(menuIcon[pos]);
        }
    }

    private class AreaAdapter extends ListBaseAdapter<Area> {

        public AreaAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.app_item_city_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_name = holder.getView(R.id.tv_name);
            tv_name.setText(mDataList.get(position).getName());
        }
    }
}
